package com.jplus.core.db;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jplus.core.db.dynamic.DynamicDataSource;

/**
 * 静态数据源工厂
 */
public final class TransactionManager {
	private final static Logger logger = LoggerFactory.getLogger(TransactionManager.class);
	private final static ThreadLocal<Connection> connection = new ThreadLocal<Connection>();
	private final static ThreadLocal<Boolean> isTransaction = new ThreadLocal<Boolean>() {
		@Override
		protected Boolean initialValue() {
			return false;
		}
	};

	private static DynamicDataSource dynamicDataSource;
	private static JdbcTemplate jdbcTemplate;

	// ===============================================================
	/**
	 * 添加数据源
	 */
	public static synchronized void addDataSource(String name, DataSource dataSource) {
		if (dynamicDataSource == null) {
			dynamicDataSource = new DynamicDataSource();
		}
		dynamicDataSource.addDataSources(name, dataSource);
	}

	public static synchronized void addDataSource(DataSource dataSource) {
		addDataSource(dataSource.getClass().getName(), dataSource);
	}

	/**
	 * 获取数据源
	 */
	public static DataSource getDynamicDataSource() {
		return dynamicDataSource;
	}
	// ===============================================================
	// ===============================================================

	/**
	 * 获取连接
	 */
	public static Connection getConnection() {
		Connection conn;
		try {
			conn = connection.get();
			if (conn == null || conn.isClosed()) {// 1
				conn = getDynamicDataSource().getConnection();
				if (conn != null) {
					connection.set(conn);
					isTransaction.set(false);// 默认为false
				}
			}
		} catch (SQLException e) {
			logger.error("获取数据库连接出错！", e);
			throw new RuntimeException(e);
		}
		return conn;
	}

	/**
	 * 开启事务
	 */
	public static void openTransaction(int level) {
		Connection conn = getConnection();
		if (conn != null) {
			try {
				conn.setAutoCommit(false);
				conn.setTransactionIsolation(level);
			} catch (SQLException e) {
				logger.error("开启事务出错！", e);
				throw new RuntimeException(e);
			} finally {
				connection.set(conn);
				isTransaction.set(true);
			}
		}
	}

	/**
	 * 提交事务
	 */
	public static void commitTransaction() {
		Connection conn = getConnection();
		if (conn != null) {
			try {
				conn.commit();
				conn.close();
			} catch (SQLException e) {
				logger.error("提交事务出错！", e);
				throw new RuntimeException(e);
			} finally {
				connection.remove();
				isTransaction.remove();
			}
		}
	}

	/**
	 * 回滚事务
	 */
	public static void rollbackTransaction() {
		Connection conn = getConnection();
		if (conn != null) {
			try {
				conn.rollback();
				conn.close();
			} catch (SQLException e) {
				logger.error("回滚事务出错！", e);
				throw new RuntimeException(e);
			} finally {
				connection.remove();
				isTransaction.remove();
			}
		}
	}

	/**
	 * 获取JdbcTemplate
	 */
	public static synchronized JdbcTemplate getJdbcTemplate() {
		if (jdbcTemplate == null) {// 2
			jdbcTemplate = new JdbcTemplate(getDynamicDataSource());
		}
		return jdbcTemplate;
	}

	public static Boolean isTransaction() {
		return isTransaction.get();
	}

	public static void openTransaction() {
		isTransaction.set(true);
	}
}
